﻿<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <title></title>

    <!-- <script src="./aframe.js"/> -->
    <script src="https://aframe.io/releases/0.7.0/aframe.js"></script>

    <!-- <script src="./aframe-event-set-component.js"/>  -->
    <script src="https://unpkg.com/aframe-event-set-component@3.0.3/dist/aframe-event-set-component.js"></script>
    <script type="text/javascript">
    </script>

    <style type="text/css">
        html,
        body,
        body>div {
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
            border: 0px;
        }

        body>div {
            display: flex;
            position: relative;
        }

        body>div>div:nth-child(1) {
            flex-grow: 1;
        }

        body>div>div:nth-child(2) {
            width: 200px;
        }

        canvas {
            cursor: default!important;
        }

        .sensor{
            border: 1px solid gray;
        }

        .tip{
            position: absolute;
            border: 1px solid gray;
        }
        
    </style>

    <script type="text/javascript">
        var sensors = {}

        const SensorColor = 'gray'
        const WarnColor = 'red'
        const FlashColor = 'yellow'


        function addSphere() {

            document.querySelector('a-plane').addEventListener('click', function (evt) {
                if (color == 'blue') {
                    color = 'green'
                } else {
                    color = 'blue'
                }
                evt.target.setAttribute('color', color)
            })

            var sphereElement = document.createElement('a-sphere')
            sphereElement.setAttribute('position', '0 4 -3')
            sphereElement.setAttribute('color', 'red')
            sphereElement.setAttribute('radius', '0.75')
            sphereElement.setAttribute('dynamic-body', '')

            var sceneElement = document.querySelector('a-scene')
            sceneElement.appendChild(sphereElement)
        }

        function addThreeJSBox() {
            var geometry = new THREE.BoxGeometry(1, 1, 1)
            var material = new THREE.MeshBasicMaterial({
                color: 0x00ff00
            })
            var cube = new THREE.Mesh(geometry, material)
            cube.position.set(0, 0.5, -4)

            var scene = document.querySelector('a-scene').object3D
            scene.add(cube)
        }

        function rotate() {
            rotation += 10
            var entityEl = document.querySelector('a-box')
            entityEl.setAttribute('rotation', '0 ' + rotation + ' 0')
        }

        function changeColor(object, sensor) {
            if (object instanceof THREE.Mesh) {
                var material = new THREE.MeshBasicMaterial({
                    color: sensor.flash ? FlashColor : (sensor.warn ? WarnColor : SensorColor)
                })
                object.material = material
            } else {
                for (var child of object.children) {
                    changeColor(child, sensor)
                }
            }
        }

        function loadObject(sceneElement, object) {
            if (object.name === 'sensor') {
                var sensorElement = document.createElement('a-entity')
                //sensorElement.setAttribute('id', object.uuid)
                sensorElement.setObject3D('entiry', object)
                var sensor = {
                    object3D: object,
                    name: 'sensor' + sensorElement.object3D.uuid.substring(0, 8),
                    value: 10,
                    warn: false,
                    flash: false,
                    selected: false
                }
                changeColor(object, sensor)

                sceneElement.appendChild(sensorElement)
                sensorElement.addEventListener('click', function (event) {
                    var element = document.querySelector('#a'+event.target.object3D.uuid)
                    var sensor = sensors[event.target.object3D.uuid]
                    sensor.selected = !sensor.selected
                    element.style.backgroundColor = sensor.selected ? 'gray' : 'transparent'
                })
                sensorElement.addEventListener('mouseenter', function (event) {
                    var sensor = sensors[event.target.object3D.uuid]
                    var tipElement = document.createElement('div')
                    tipElement.setAttribute('class', 'tip')
                    tipElement.style.left = x.toString() + 'px'
                    tipElement.style.top = y.toString() + 'px'
                    tipElement.innerHTML = `\
                        <div>\
                            传感器名字: ${sensor.name}\
                        </div>\
                        <div>\
                            传感器值: ${sensor.value}\
                        </div>`
                    var rootElement = document.querySelector('.root')
                    rootElement.appendChild(tipElement)
                })
                sensorElement.addEventListener('mouseleave', function (event) {
                    var tipElement = document.querySelector('.tip')
                    if(tipElement){
                        var rootElement = document.querySelector('.root')
                        rootElement.removeChild(tipElement)
                    }
                })
                sensors[sensorElement.object3D.uuid.toString()] = sensor
            } else {
                var scene = sceneElement.object3D
                scene.add(object)
            }
        }

        function loadGLTF() {
            // Instantiate a loader
            var loader = new THREE.GLTFLoader()

            // Optional: Provide a DRACOLoader instance to decode compressed mesh data
            // THREE.DRACOLoader.setDecoderPath( '/examples/js/libs/draco' );
            // loader.setDRACOLoader( new THREE.DRACOLoader() )

            // Load a glTF resource
            loader.load(
                // resource URL
                'test.gltf',
                // called when the resource is loaded
                function (gltf) {

                    var sceneElement = document.querySelector('a-scene')

                    var children = gltf.scene.children[0].children.slice(0)
                    console.log(children)
                    for (var child of children) {
                        loadObject(sceneElement, child)
                    }

                    var informationElement = document.querySelector('#information')
                    for(var id in sensors){
                        var sensorElement = document.createElement('div')
                        sensorElement.setAttribute('class', 'sensor')
                        var sensor=sensors[id]

                        sensorElement.innerHTML = `\
                            <div id='a${id}' class='sensor'>\
                                <div>\
                                    传感器名字: ${sensor.name}\
                                </div>\
                                <div>\
                                    传感器值: ${sensor.value}\
                                </div>\
                                <button onclick='flash("${id}")'>闪烁/停止</button>\
                                <button onclick='warn("${id}")'>报警/停止</button>\
                            </div>`
                        informationElement.appendChild(sensorElement)
                    }

                    // scene.add(gltf.scene)

                    // gltf.animations // Array<THREE.AnimationClip>
                    // gltf.scene // THREE.Scene
                    // gltf.scenes // Array<THREE.Scene>
                    // gltf.cameras // Array<THREE.Camera>
                    // gltf.asset // Object
                },
                // called while loading is progressing
                function (xhr) {
                    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
                },
                // called when loading has errors
                function (error) {
                    console.log(error)
                }
            )
        }

        function doFlash(id){
            var sensor = sensors[id]
            sensor.flash = !sensor.flash
            changeColor(sensor.object3D, sensor)
        }

        function flash(id){
            var sensor = sensors[id]
            if(sensor.timerId){
                clearInterval(sensor.timerId)
                sensor.timerId = null
                sensor.flash = false
                changeColor(sensor.object3D, sensor)
            }else{
                sensor.timerId = setInterval(doFlash.bind(id, id), 1000)
            }
        }

        function warn(id){
            var sensor = sensors[id]
            sensor.warn = !sensor.warn
            changeColor(sensor.object3D, sensor)
        }

        function onLoad() {
            console.log('-----------------------------------------------')
            console.log(THREE)
            console.log(AFRAME)
            console.log('-----------------------------------------------')

            // var rotation = 45
            // var color = 'blue'
            // AFRAME.registerComponent('enum-children', {
            //     init: function () {
            //         this.el.addEventListener('model-loaded', () => {
            //             // Grab the mesh / scene.
            //             const root = this.el.getObject3D('mesh');
            //             console.log(root)
            //             for (var child of root.children) {
            //                 console.log(child)
            //             }
            //         })
            //     }
            // })

            //setTimeout(addSphere, 500)
            //setTimeout(addThreeJSBox, 1000)
            //setInterval(rotate, 1000)

            loadGLTF()
        }

        function onMouseover(){
            x = window.event.clientX 
            y = window.event.clientY - 50
            console.log(x)
            console.log(y)
        }

    </script>
</head>

<body onload='onLoad()' onmousemove='onMouseover()'>
    <div class='root'>
        <div>

            <a-scene debug vr-mode-ui='enabled:false' inspector='' embedded>
                <!-- <a-assets>
                                    <a-asset-item id="tree" src="tree.gltf">
                                </a-assets> -->

                <!-- <a-entity position="0 1.8 4">
                                    <a-entity camera look-controls mouse-cursor>
                                      <a-cursor fuse="true" color="yellow"></a-cursor>
                                    </a-entity>
                                </a-entity> -->
                <a-camera cursor='rayOrigin: mouse' look-controls>

                </a-camera>

                <!-- <a-box position='0 4 -3' rotation='0 45 0' color='red' dynamic-body
                    event-set__click='_event: click; color: green'>
                </a-box> -->
                <a-plane position='0 0 -4' rotation='-90 0 0' width='4' height='4' color='blue' static-body></a-plane>
                <a-sky color='#ECECEC'></a-sky>

                <!-- <a-gltf-model enum-children src='test.gltf'></a-gltf-model> -->

            </a-scene>
        </div>
        <div id='information'>

        </div>
    </div>
</body>

</html>